#!/bin/gawk -f
# sorts Aqua restraint file on atom name pairs

BEGIN {
    print "Z = QQ,  R = aromatic Q,  RR = QR"
}

NR == 1 {
#    print $0
    next
}

NR == 2 {
#    print $0
    count = $2
    next
}

/^#/ { next }

{
    nam1 = $4
    if ( $2 == "PHE" || $2 == "TYR" ) {
	if ( $4 == "QD" || $4 == "QE" ) 
	    nam1 = "R"
	if ( $4 == "QR" ) 
	    nam1 = "RR"
    }
    nam2 = $7
    if ( $5 == "PHE" || $5 == "TYR" ) {
	if ( $7 == "QD" || $7 == "QE" ) 
	    nam2 = "R"
	if ( $7 == "QR" ) 
	    nam2 = "RR"
    }
    sub( /^[1-3]?H.*/, "H", nam1 )
    sub( /^QQ.*/, "Z", nam1 )
    sub( /^Q.*/, "Q", nam1 )
    sub( /^[1-3]?H.*/, "H", nam2 )
    sub( /^QQ.*/, "Z", nam2 )
    sub( /^Q.*/, "Q", nam2 )
    if ( nam2 < nam1 ) {
	nam = nam1
	nam1 = nam2
	nam2 = nam
    }
    item = nam1"-"nam2
    array[item]++
    if ( NF == 8 )
	print item, $8 > "tmp.range"
    else if ( NF == 9 )
	print item, $8, $9 > "tmp.range"
}

END {
    for ( item in array ) {
        print item " " array[item]
	tot += array[item]
    }
    if ( tot != count )
	print "ERROR: count", count, "tot", tot
}
